#!/usr/bin/env python3
###
# @Author: Logan.Li
# @Gitee: https://gitee.com/attacker
# @email: admin@attacker.club
# @Date: 2025-03-14 09:50:30
# @LastEditTime: 2025-03-14 09:50:35
# @Description: 华为云监控主程序
###

import os
import sys
import json
import logging
import configparser
from typing import Dict
from compute.ecs_monitor import ECSMonitor
from compute.cce_monitor import CCEMonitor

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

class HuaweiCloudMonitorSystem:
    """华为云监控系统"""
    
    def __init__(self, config_file: str = 'config.ini'):
        """初始化监控系统
        
        Args:
            config_file: 配置文件路径
        """
        self.config = self._load_config(config_file)
        self.monitors = self._init_monitors()
        
    def _load_config(self, config_file: str) -> Dict:
        """加载配置文件"""
        if not os.path.exists(config_file):
            logging.error(f"配置文件不存在: {config_file}")
            sys.exit(1)
            
        config = configparser.ConfigParser()
        config.read(config_file)
        
        # 只需要基础配置
        return {
            'access_key': config['huaweicloud']['access_key'],
            'secret_key': config['huaweicloud']['secret_key'],
            'region': config['huaweicloud']['region']
        }
        
    def _init_monitors(self) -> Dict:
        """初始化监控模块"""
        return {
            'ecs': ECSMonitor(self.config),
            'cce': CCEMonitor(self.config)
        }
        
    def check_resource_status(self):
        """检查资源状态"""
        try:
            # 检查ECS状态
            ecs_status = self.monitors['ecs'].monitor_all_instances()
            if ecs_status['abnormal_count'] > 0:
                logging.warning(f"发现{ecs_status['abnormal_count']}个异常ECS实例")
                logging.warning("Top异常实例:")
                for instance in ecs_status['top_abnormal']:
                    logging.warning(
                        f"实例: {instance['name']}({instance['id']}) "
                        f"指标: {instance['metric']} "
                        f"当前值: {instance['value']:.2f}%"
                    )
            else:
                logging.info(f"ECS实例状态正常，共{ecs_status['total_instances']}个实例")
                
            # 检查CCE状态
            cce_status = self.monitors['cce'].monitor_all_clusters()
            if cce_status['abnormal_nodes']:
                logging.warning(f"发现{len(cce_status['abnormal_nodes'])}个异常CCE节点")
                logging.warning("Top异常节点:")
                for node in cce_status['abnormal_nodes']:
                    logging.warning(
                        f"集群: {node['cluster']} "
                        f"节点: {node['node']} "
                        f"指标: {node['metric']} "
                        f"当前值: {node['value']:.2f}%"
                    )
            else:
                logging.info(f"CCE集群状态正常，共{cce_status['total_clusters']}个集群")
                
            # 输出集群状态
            for cluster in cce_status['cluster_status']:
                if cluster['status'] != 'Available':
                    logging.warning(
                        f"集群状态异常: {cluster['name']}({cluster['id']}) "
                        f"状态: {cluster['status']}"
                    )
                    
        except Exception as e:
            logging.error(f"监控检查失败: {e}")
            return False
            
        return True

def main():
    """主函数"""
    # 获取脚本所在目录
    script_dir = os.path.dirname(os.path.abspath(__file__))
    config_file = os.path.join(script_dir, 'config.ini')
    
    # 初始化监控系统
    monitor_system = HuaweiCloudMonitorSystem(config_file)
    
    # 运行监控检查
    monitor_system.check_resource_status()

if __name__ == "__main__":
    main()
